<template>
    <div class="map-container">
      <el-row :gutter="20">
        <!-- 左侧查询面板 -->
        <el-col :span="8">
          <el-card class="map-card">
            <template #header>
              <div class="card-header">
                <span>地图服务</span>
              </div>
            </template>
            
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
              <!-- 保险公司查询标签页 -->
              <el-tab-pane label="保险公司查询" name="insurance">
                <el-form :model="searchForm" label-width="80px">
                  <el-form-item label="城市">
                    <el-input v-model="searchForm.city" placeholder="如：北京、上海" />
                  </el-form-item>
                  
                  <el-form-item label="保险公司">
                    <el-select v-model="searchForm.type" placeholder="请选择">
                      <el-option label="中国人寿" value="中国人寿" />
                      <el-option label="新华人寿" value="新华人寿" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="searchInsurance">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                  </el-form-item>
                </el-form>
                
                <el-divider />
                
                <div v-loading="loading" class="result-container">
                  <el-empty v-if="!insuranceLocations.length" description="暂无数据" />
                  
                  <el-table 
                    v-else 
                    :data="insuranceLocations" 
                    height="300" 
                    border 
                    style="width: 100%"
                    @row-click="handleRowClick"
                  >
                    <el-table-column prop="name" label="名称" width="120" />
                    <el-table-column prop="address" label="地址" />
                    <el-table-column prop="tel" label="电话" width="120" />
                    <el-table-column label="图片" width="120">
                      <template #default="scope">
                        <el-image 
                          v-if="scope.row.photos && scope.row.photos.length > 0"
                          style="width: 100px; height: 60px"
                          :src="scope.row.photos[0]" 
                          :preview-src-list="scope.row.photos"
                          hide-on-click-modal
                          fit="cover"
                        />
                        <span v-else>暂无图片</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-tab-pane>
              
              <!-- 用户位置查询标签页 -->
              <el-tab-pane label="我的位置" name="user">
                <div class="user-location-container">
                  <el-button 
                    type="primary" 
                    @click="searchUserLocation"
                    :loading="loading"
                  >
                    查询我的位置
                  </el-button>
                </div>
                <div v-if="userLocationData" class="user-address">
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="用户地址">{{ userLocationData.address || '未知地址' }}</el-descriptions-item>
                    <el-descriptions-item label="坐标位置">{{ userLocationData.location }}</el-descriptions-item>
                  </el-descriptions>
                  
                  <div class="map-image-preview">
                    <el-image 
                      style="width: 100%; height: 200px; margin-top: 10px;"
                      :src="userLocationData.image_url" 
                      :preview-src-list="[userLocationData.image_url]"
                      fit="contain"
                    />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
        
        <!-- 右侧地图展示 -->
        <el-col :span="16">
          <el-card class="map-card">
            <template #header>
              <div class="card-header">
                <span>地图展示</span>
              </div>
            </template>
            
            <div id="map-container" style="height: 600px; width: 100%">
              <div v-if="!mapLoaded" class="map-placeholder">
                <el-icon><MapLocation /></el-icon>
                <p>请先进行查询操作</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { MapLocation } from '@element-plus/icons-vue'
  import axios from 'axios'
  
  // 高德地图API加载
  const loadAMap = () => {
    return new Promise((resolve, reject) => {
      if (window.AMap) {
        resolve()
        return
      }
      
      const script = document.createElement('script')
      script.src = `https://webapi.amap.com/maps?v=2.0&key=b582711bf3d653f4fc72926275977e17`
      script.onload = resolve
      script.onerror = () => reject(new Error('高德地图加载失败'))
      document.head.appendChild(script)
    })
  }
  
  // 状态管理
  const activeTab = ref('insurance')
  const loading = ref(false)
  const mapLoaded = ref(false)
  let map = null
  let markers = []
  
  // 表单数据
  const searchForm = ref({
    city: '',
    type: '中国人寿'
  })
  
  // 结果数据
  const insuranceLocations = ref([])
  const userLocationData = ref(null)
  
  // 初始化地图
  const initMap = async () => {
    try {
      await loadAMap()
      
      if (!window.AMap) {
        throw new Error('高德地图加载失败')
      }
  
      if (!map) {
        map = new AMap.Map('map-container', {
          zoom: 12,
          center: [116.397428, 39.90923]
        })
        mapLoaded.value = true
      }
    } catch (error) {
      ElMessage.error(error.message)
    }
  }
  
  // 组件挂载时初始化地图
  onMounted(() => {
    initMap()
  })
  
  // 解析位置字符串为经纬度数组
  const parseLocation = (locationStr) => {
    if (!locationStr) return null
    
    const [lngStr, latStr] = locationStr.split(',')
    const lng = parseFloat(lngStr.trim())
    const lat = parseFloat(latStr.trim())
    
    if (isNaN(lng) || isNaN(lat)) {
      throw new Error('无效的坐标格式')
    }
    
    return [lng, lat]
  }
  
  // 查询保险公司位置
  const searchInsurance = async () => {
    if (!searchForm.value.city) {
      ElMessage.warning('请输入城市名称')
      return
    }
  
    try {
      loading.value = true
      const response = await axios.post('http://127.0.0.1:8000/ai/map_info/', {
        city: searchForm.value.city,
        types: searchForm.value.type
      })
      
      if (response.data.status === 'success' && response.data.data.status === '1') {
        insuranceLocations.value = response.data.data.pois.map(poi => ({
          name: poi.name,
          address: poi.address,
          tel: poi.tel || '暂无',
          location: poi.location,
          photos: poi.photos || []
        }))
        
        if (insuranceLocations.value.length > 0) {
          await initMap()
          showLocationsOnMap(insuranceLocations.value)
          ElMessage.success(`找到${insuranceLocations.value.length}个结果`)
        } else {
          ElMessage.info('未查询到相关保险公司')
        }
      } else {
        ElMessage.error(response.data.message || '查询失败')
      }
    } catch (error) {
      ElMessage.error('请求出错：' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 查询用户位置
  const searchUserLocation = async () => {
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.warning('未获取到用户ID，请先登录')
      return
    }
  
    try {
      loading.value = true
      const response = await axios.post('http://127.0.0.1:8000/ai/map_img/', {
        userid: userId
      })
      
      if (response.data.status === 'success' && response.data.data.code === 10000) {
        const responseData = response.data.data.data
        userLocationData.value = {
          address: responseData.address,
          location: responseData.location,
          image_url: responseData.image_url
        }
        
        // 解析坐标
        const coords = parseLocation(responseData.location)
        if (!coords) {
          throw new Error('无法解析位置坐标')
        }
        
        // 显示地图
        await initMap()
        clearMap()
        
        // 添加标记点
        const marker = new AMap.Marker({
          position: coords,
          title: '用户位置',
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
        })
        
        // 信息窗口内容
        const infoContent = `
          <div class="map-info-window">
            <h4>用户位置</h4>
            <p>${userLocationData.value.address || '未知地址'}</p>
            <p>坐标: ${userLocationData.value.location}</p>
          </div>
        `
        
        // 显示地图和标记
        map.add(marker)
        map.setCenter(coords)
        map.setZoom(15)
        
        // 显示信息窗口
        new AMap.InfoWindow({
          content: infoContent,
          offset: new AMap.Pixel(0, -30)
        }).open(map, coords)
        
        markers.push(marker)
      } else {
        ElMessage.error(response.data.message || '查询失败')
      }
    } catch (error) {
      ElMessage.error('地图加载失败: ' + error.message)
      console.error('地图加载错误:', error)
    } finally {
      loading.value = false
    }
  }
  
  // 在地图上显示保险公司位置
  const showLocationsOnMap = (locations) => {
    clearMap()
    
    locations.forEach(location => {
      try {
        const coords = parseLocation(location.location)
        if (!coords) return
        
        const marker = new AMap.Marker({
          position: coords,
          title: location.name
        })
        
        marker.on('click', () => {
          const photoContent = location.photos.length > 0 
            ? `<img src="${location.photos[0]}" style="max-width:200px;max-height:150px;margin-top:10px;">` 
            : ''
          
          new AMap.InfoWindow({
            content: `
              <div class="map-info-window">
                <h4>${location.name}</h4>
                <p>地址：${location.address}</p>
                <p>电话：${location.tel}</p>
                ${photoContent}
              </div>
            `,
            offset: new AMap.Pixel(0, -30)
          }).open(map, coords)
        })
        
        markers.push(marker)
      } catch (e) {
        console.error('无效的位置数据:', location.location)
      }
    })
    
    if (markers.length > 0) {
      map.add(markers)
      map.setFitView()
    }
  }
  
  // 清除地图标记
  const clearMap = () => {
    if (map && markers.length > 0) {
      map.remove(markers)
      markers = []
    }
  }
  
  // 表格行点击事件
  const handleRowClick = (row) => {
    if (row.location && map) {
      try {
        const coords = parseLocation(row.location)
        if (coords) {
          map.setCenter(coords)
          map.setZoom(15)
        }
      } catch (e) {
        console.error('无效的位置数据:', row.location)
      }
    }
  }
  
  // 重置查询
  const resetSearch = () => {
    searchForm.value = { city: '', type: '中国人寿' }
    insuranceLocations.value = []
    clearMap()
  }
  
  // 标签页切换事件
  const handleTabChange = (tab) => {
    if (tab.paneName === 'user') {
      searchUserLocation()
    }
  }
  </script>
  
  <style scoped>
  .map-container {
    padding: 20px;
    height: 100%;
  }
  
  .map-card {
    height: 100%;
  }
  
  .card-header {
    font-size: 18px;
    font-weight: bold;
  }
  
  .result-container {
    margin-top: 10px;
  }
  
  .map-placeholder {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #999;
  }
  
  .map-placeholder .el-icon {
    font-size: 50px;
    margin-bottom: 10px;
  }
  
  .user-address {
    margin-top: 20px;
  }
  
  .user-location-container {
    margin-bottom: 20px;
    text-align: center;
  }
  
  .map-image-preview {
    margin-top: 15px;
    border: 1px solid #ebeef5;
    padding: 10px;
    border-radius: 4px;
  }
  
  :deep(.el-image) {
    cursor: pointer;
  }
  </style>